package com.lagou.work4;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;
/*
    flink state案例
 */

public class StateDemo {
    public static void main(String[] args) throws Exception {
        //设置flink 执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.enableCheckpointing(2000);
        //获取数据
        DataStreamSource<String> data = env.socketTextStream("server1", 9099);
        //处理数据
        SingleOutputStreamOperator<Tuple2<Long,Long>> maped = data.map(
                new MapFunction<String, Tuple2<Long, Long>>() {
                    @Override
                    public Tuple2<Long, Long> map(String s) throws Exception {
                        String[] s1 = s.split(",");
                        return new Tuple2<>(Long.valueOf(s1[0]),Long.valueOf(s1[1]));
                    }
                }
        );
        KeyedStream<Tuple2<Long, Long>, Long> keyed = maped.keyBy(value -> value.f0);
        //按key分组，对流数据调用状态化处理
        SingleOutputStreamOperator<Tuple2<Long,Long>> outputStreamOperator = keyed.flatMap(
                new RichFlatMapFunction<Tuple2<Long, Long>, Tuple2<Long, Long>>() {
                    ValueState<Tuple2<Long, Long>> sumState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        //在open方法中实例出一个状态实例
                        ValueStateDescriptor<Tuple2<Long,Long>> descriptor = new ValueStateDescriptor<Tuple2<Long, Long>>(
                                "average",
                                TypeInformation.of(new TypeHint<Tuple2<Long, Long>>() {
                                }),
                                Tuple2.of(0L, 0L)
                        );
                        sumState = getRuntimeContext().getState(descriptor);
                        super.open(parameters);
                    }

                    @Override
                    public void flatMap(Tuple2<Long, Long> longLongTuple2, Collector<Tuple2<Long, Long>> collector) throws Exception {
                        //在flatmap方法中，随着流数据来更新state
                        Tuple2<Long, Long> currentSum = sumState.value();
                        currentSum.f0 += 1;
                        currentSum.f1 += longLongTuple2.f1;

                        sumState.update(currentSum);
                        if(currentSum.f0 == 2){
                            long average = currentSum.f1 / currentSum.f0;
                            collector.collect(new Tuple2<>(longLongTuple2.f0, average));
                            sumState.clear();
                        }

                    }
                }
        );

        //输出结果
        outputStreamOperator.print();
        env.execute();
    }
}
